<template>
  <div class="page--call">
    <div class="page--cal__desc">请确保当前设备有耳麦或者话筒，否则会造成呼叫工具条启动不成功！！！
      <el-button style="padding:3px 5px" size="mini" type="primary" icon="el-icon-s-tools" @click="checkNotification()">
        通知设置
      </el-button>
    </div>
    <iframe width="100%" height="100%" name="toolbar" id="toolbar" scrolling="no" frameborder="0"
      src="/agent-sdk/toolbar.html" class="callIframe"></iframe>
    <el-dialog title="回呼用户信息" :visible.sync="dialogVisible" :append-to-body="false" width="500px" center :modal="false">
      <div class="callRingDialog ta-center">
        <p class="ta-center">
          <span class="callRingDialog__user-logo"><i class="el-icon-user"></i></span>
        </p>
        <p class="callRingDialog__number">{{ ringInfo.customerNumber | telAnonymity }}</p>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="座席工号">{{ ringInfo.cno || "" }}</el-descriptions-item>
          <el-descriptions-item label="号码区号">{{ ringInfo.customerAreaCode || "" }}</el-descriptions-item>
          <template>
            <el-descriptions-item label="客户ID">{{ customerOrderInfo.crmId || "-" }}</el-descriptions-item>
            <el-descriptions-item label="订单号">{{ customerOrderInfo.orderId || "-" }}</el-descriptions-item>
            <el-descriptions-item label="渠道订单号">{{ customerOrderInfo.coopOrderID || "-" }}</el-descriptions-item>
          </template>
        </el-descriptions>
        <p>请在页面底部外呼工具条中接听电话！</p>
      </div>
      <span slot="footer" class="dialog-footer">
        <!-- <el-button @click="dialogVisible = false">取 消</el-button>-->
        <el-button type="primary" @click="closeButton">知道了</el-button>
      </span>

    </el-dialog>
    <!--    <div class="devToolBox" v-if="showToolBar">
      <el-row>
        <el-col :span="8">
          <el-button type="success" size="small" @click="getCallStatus">获取call状态</el-button>
          <el-button type="primary" size="small" @click="dialogVisible=true">弹屏</el-button>
          <el-button type="primary" size="small" @click="agentAutoLogin">模拟自动登录</el-button>
&lt;!&ndash;          <el-button type="danger" size="small" @click="agentAutoCall({tel:'13366281808'})">模拟自动打电话</el-button>&ndash;&gt;
        </el-col>
        <el-col :span="6">
          <el-input v-model="tel" placeholder="手机号" style="width: 150px;"></el-input>
          <el-button type="danger" size="small" @click="tel && agentAutoCall({tel})">模拟自动打电话</el-button>
        </el-col>
      </el-row>
    </div>-->
  </div>
</template>

<script>
import { mapGetters, mapActions, mapState } from "vuex"
import { getCallBackCustomerInfo } from "@/api/call/call"
export default {
  name: "Call",
  data() {
    return {
      iframeDom: null,
      dialogVisible: false,
      ringInfo: {},
      tel: "",
      showToolBar: location.host === 'localhost',
      customerNumberTypeText: {
        1: "固话",
        2: "手机"
      },
      styleChange: {
        height: "",
        //width: "",
      },
      customerOrderInfo: {}
    };
  },
  computed: {
    ...mapState("call", ["isAutoLoginCall"]),
    ...mapState({
      agentId: state => state.user.agentId,
    }),
  },
  created() {
    //console.log("外呼组件重新渲染了");
    // 检测浏览器是否支持通知事件 如果支持就提示用户
    this.checkNotification(true);
  },
  watch: {},
  async mounted() {
    const that = this;
    //that.styleChange.height = window.innerHeight + "px"; // 屏幕高度
    //that.styleChange.width = window.innerWidth + "px"; // 屏幕宽度
    await this.getCallLoginConfig({});
    await this.init();
  },
  methods: {
    ...mapActions('call', ["getCallLoginConfig", "callStateResult", "agentAutoLogin", "agentAutoCall", "handleLogin", "handleKickout", "toggleOpen", "initCallBarAccount"]),
    handleState(data) {
      this.callStateResult(data)
    },
    init() {
      //call事件回调信息查看 https://wiki.cticloud.cn/toolbarIndex.html?page=/html/wiki/%E5%B7%A5%E5%85%B7%E6%9D%A1/%E4%BA%8B%E4%BB%B6.html
      this.iframeDom = document.getElementById('toolbar').contentWindow || null;
      window.handleState = this.handleState;     //监听坐席状态
      window.cbRinging = this.cbRinging;       //响铃 弹屏
      window.handleLogin = this.handleLogin;     //登录
      window.handleKickout = this.handleKickout; //被踢下线

      //避免iframe加载不出来，延时设置 外呼自动登录
      this.isAutoLoginCall && setTimeout(() => {
        this.agentAutoLogin()
      }, 3000)
    },
    //cbRinging为响铃事件的回调，弹屏可以在这显示相关逻辑
    cbRinging(data) {
      console.log("响铃事件的回调", JSON.stringify(data, null, 2))
      this.ringInfo = data || {};
      // callType:1是呼入， callType:5是转接
      if (data.callType === 1 || data.callType === 5) {

        // 监听到有响铃打开呼叫条
        this.toggleOpen({
          open: true
        });

        // 通知浏览器
        this.notification(data);

        // 请求用户，并跳转到用户详情页
        this.getCustomerOrder({
          mobile: data.customerNumber,
          agentId: data.cno
        });
      }

    },
    // 浏览器通知事件
    notification(ringInfo) {
      if (window.Notification && Notification.permission !== "denied") {
        Notification.requestPermission(function (status) {
          var n = new Notification(`${ringInfo.customerNumber} 来电` || '来电话了', { body: `${ringInfo.customerNumber || ''}正在呼叫，请坐席回到scrm系统接听！` });
        }).catch(function() {
        });
    }
    },
    checkNotification(first) {
      let ntf = window.Notification;
      console.log(ntf.permission);
      if (!ntf && !first) {
        this.$message({
          type: 'danger',
          message: "当前浏览器不支持来电消息推送，请下载最新版谷歌浏览器（chrome）！"
        })
        return
      }
      // 初次使用提示
      if (first) {
        if (ntf && Notification.permission == "default") {
          ntf.requestPermission();
        }
        return
      }
      // 未提示
      if (ntf.permission == "default") {
        this.$message("请在浏览器弹出的通知消息弹窗点击【允许】！");
        ntf.requestPermission();
      }
      // 已启用
      if (ntf.permission == "granted") {
        this.$message("您已经启用来电通知功能！")
      }
      // 已禁止
      if (ntf.permission == "denied") {
        ntf.requestPermission();
        this.$alert('您已经禁止本网站通知功能，请在浏览器设置>隐私设置>（网站设置或内容设置）> 权限通知中请允许本网站', '温馨提示', {
          confirmButtonText: '知道了',
          callback: action => { }
        });
      }
    },
    async getCustomerOrder(query) {
      if (!query.mobile) {
        console.log("回响参数有误请检查");
        return
      }
      await getCallBackCustomerInfo(query).then((response) => {
        this.customerOrderInfo = response.data || {};
        console.log("allowDetail="+this.customerOrderInfo.allowDetail);

        if (this.customerOrderInfo.crmId == undefined) {
          // 显示用户信息弹框
          this.dialogVisible = true;
        } else {
          // 跳转
          this.$router.push({
            path: '/crm/customerDetail/index',
            query: { crmId: btoa(this.customerOrderInfo.crmId), t: Date.now()}
          })
        }
      })
    },
    getCallStatus() {
      console.log("在线状态", this.iframeDom.isOnline)
      console.log("通话状态", this.iframeDom.CTILink.Session.isSessionAlive())
    },

    /**
     * 知道了按钮 跳转
     */
    closeButton() {
      console.log("点击知道了 crmId="+this.customerOrderInfo.crmId)
      console.log("点击知道了 跳转="+this.customerOrderInfo.allowDetail)
      if (this.customerOrderInfo.allowDetail == 1) {
        this.$router.push({
          path: '/crm/customerDetail/index',
          query: { crmId: btoa(this.customerOrderInfo.crmId) }
        })
      }
      this.dialogVisible = false;
    }
  },
  beforeDestroy() {

  },

};
</script>
<style lang="scss" scoped>
.page--call {
  width: 100%;
  height: 170px;
  background: #f0f0f0;
}

.callIframe {
  width: 100%;
  height: 100%;
  border: solid 1px #ddd;
}

.devToolBox {
  position: absolute;
  bottom: 0;
  width: 100%;
}

.callRingDialog {
  &__user-logo {
    display: inline-block;
    padding: 10px;
    width: 60px;
    height: 60px;
    border-radius: 50%;
    background: #00afff;
    text-align: center;
    font-size: 32px;
    color: #fff;
  }

  &__number {
    text-align: center;
    font-size: 22px;
    font-weight: bold;
  }
}

.page--cal__desc {
  padding: 5px;
  text-align: center;
  font-size: 14px;
  color: red;
  font-weight: bold;
}

.inMobile .page--call {
  height: 60vh;
}
</style>
